package com.itms.tool;

import java.sql.SQLException;
import java.util.List;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.WindowManager;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.itms.tool.data.Object;
import com.itms.tool.utils.SimpleTabListener;
import com.itms.tool.utils.ViewPager;
import com.itms.tool.utils.ViewPager.SimpleOnPageChangeListener;

public class NewObjectActivity extends BaseActivity {

	private static final String IMAGE_SELECTION_MODE_ENABLED = "image_selection_mode_enabled";

	private static final String PAGE_POSITION = "page_position";

	private Object mObject;
	private boolean mSent;
	
	private boolean mSmallScreen; // width smaller than 600dp
	private boolean mImageSelectionModeEnabled;
	
	// small screen widgets
	private ViewPager mViewPager;
	private int mPagePosition = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			mImageSelectionModeEnabled = savedInstanceState.getBoolean(IMAGE_SELECTION_MODE_ENABLED);
		}
		setContentView(R.layout.activity_new_object);
		setupSoftInputModeCompat();
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mSmallScreen = mViewPager != null;
		if (mSmallScreen) {
			setupSmallScreen(savedInstanceState);
		} else {
			setupLargeScreen(savedInstanceState);
		}
		try {
			mObject = getMostRecentUnSent();
		} catch (SQLException e) {
			throw new RuntimeException(e); 
		}
		if (mObject == null) {
			mObject = new Object();
			saveObject(mObject);
		}
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupSoftInputModeCompat() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
					| 
					WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
		} else {
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		}
	}

	private void setupSmallScreen(Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			mPagePosition = savedInstanceState.getInt(PAGE_POSITION);
		}
		setupPager();
		setupTabs();
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
	}

	private void setupPager() {
		mViewPager.setAdapter(new ThreePageAdapter(getSupportFragmentManager()));
		mViewPager.setOnPageChangeListener(new SimpleOnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				if (position != mPagePosition) {
					mPagePosition = position;
					getSupportActionBar().getTabAt(position).select();
				}
			}
		});
	}

	private void setupTabs() {
		TabListener tabListener = new SimpleTabListener() {
			@Override
			public void onTabSelected(Tab tab, FragmentTransaction ft) {
				if (mViewPager != null) {
					mViewPager.setCurrentItem(tab.getPosition());
				}
			}
		};
		ActionBar ab = getSupportActionBar();
		ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		Tab primaryTab = ab.newTab().setText(R.string.primary).setTabListener(tabListener);
		Tab imagesTab = ab.newTab().setText(R.string.images).setTabListener(tabListener);
		Tab secondaryTab = ab.newTab().setText(R.string.secondary).setTabListener(tabListener);
		ab.addTab(primaryTab);
		ab.addTab(imagesTab);
		ab.addTab(secondaryTab);
		if (mPagePosition != -1) {
			// if state is being restored
			ab.getTabAt(mPagePosition).select();
		} else {
			ab.getTabAt(0).select();
		}
	}

	private void setupLargeScreen(Bundle savedInstanceState) {
		if (savedInstanceState == null) {
			PrimaryFragment pf = new PrimaryFragment();
			SecondaryFragment sf = new SecondaryFragment();
			getSupportFragmentManager().beginTransaction()
					.add(R.id.primary_fragment_container, pf)
					.add(R.id.secondary_fragment_container, sf).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mImageSelectionModeEnabled) {
			getSupportMenuInflater().inflate(R.menu.new_object, menu);
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.send:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void setImageSelectionModeEnabled(boolean value) {
		if (mImageSelectionModeEnabled != value) {
			mImageSelectionModeEnabled = value;
			invalidateActionBar();
		}
	}
	
	public boolean isImageSelectionModeEnabled() {
		return mImageSelectionModeEnabled;
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void invalidateActionBar() {
		invalidateOptionsMenu();
	}
	
	public Object getObject() {
		if (mObject == null) {
			throw new IllegalStateException(getClass() + " onCreate has not been called yet");
		}
		return mObject;
	}
	
	private Object getMostRecentUnSent() throws SQLException {
		List<Object> objects = getHelper().getObjectDao().queryBuilder()
								.orderBy(Object.DATE_CREATED, false)
								.where()
								.eq(Object.IS_SENT, false)
								.query();
		if (objects.size() > 0) {
			return objects.get(0);
		}
		return null;
	}

	private void saveObject(Object object) {
		getHelper().getObjectDao().createOrUpdate(object);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mObject.setSent(mSent);
		saveObject(mObject);
	}

	@Override
	public void onBackPressed() {
		if (mImageSelectionModeEnabled) {
			setImageSelectionModeEnabled(false);
		} else {
			super.onBackPressed();
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (mSmallScreen) {
			outState.putInt(PAGE_POSITION, mPagePosition);
		}
		outState.putBoolean(IMAGE_SELECTION_MODE_ENABLED, mImageSelectionModeEnabled);
	}

}
